﻿/*
// +----------------------------------------------------------------------------+
// |                                                                            |
// |  Copyright (1999-2010) by Actify, Inc.                                     |
// |                                                                            |
// |  This program is proprietary with Actify, Inc., and is not to              |
// |  be reproduced or transmitted in any form or by any means or used in any   |
// |  manner except as authorized in writing by Actify, Inc.                    |
// |                                                                            |
// +----------------------------------------------------------------------------+
// |                                                                            |
// |   File Name : MainPage.xaml.cs                                             |
// |  Written By : Clay Tornquist                                               |
// |        Date : Feb 09 2010                                                  |
// | Description :                                                              |
// |                                                                            |
// +----------------------------------------------------------------------------+
// |                                                                            |
// | Notes:                                                                     |
// |                                                                            |
// +----------------------------------------------------------------------------+

	Changes:
		[2010-02-09 CMT] - Initial implementation.

*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Browser;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Linq;

namespace SpinFireSL
{
	public partial class MainPage : UserControl
	{
		#region Definitions

		internal enum MouseState
		{
			Rotate, 
			Zoom,
			Pan
		}

		#endregion

		#region Attributes

		private MouseState _leftMouseState = MouseState.Rotate;
		private HtmlElement _viewBrowser;
		private string _markupType;
		private string _markupName;
		private bool _markuploading = false;
		private ResourceHelper _rh = new ResourceHelper();
		private GridLength _treeWidthZero = new GridLength (0);
		private GridLength _splitterWidthZero = new GridLength (0);
		private GridLength _treeWidthLast;
		private GridLength _splitterWidthLast;
		private Cursor _current;
		private Color _color;
		private ScriptObject _lasthighlighted = null;

		private ObservableCollection<TreeItem> PartItems = new ObservableCollection<TreeItem>();
		private TreeItem GeometryTreeItems;
		private TreeItem MarkupTreeItems;
		private TreeItem ViewsTreeItems;

		private Telerik.Windows.Controls.RadMenuItem _toAddRmi;
		private Telerik.Windows.Controls.RadTreeView _shown = null;


		#endregion

		#region Constructor

		public MainPage()
		{
			InitializeComponent();
			_treeWidthLast = _treeWidthZero;
			_splitterWidthLast = _splitterWidthZero;
			ScriptableManagedType smt = new ScriptableManagedType(this);
			HtmlPage.RegisterScriptableObject("SL_SMT", smt);
			GeometryTreeItems = new TreeItem("Geometry", Color.FromArgb(0, 0, 0, 0), "", TreeItem.TreeItemType.Geometry);
			MarkupTreeItems = new TreeItem("Markup", Color.FromArgb(0, 0, 0, 0), "", TreeItem.TreeItemType.Markup);
			ViewsTreeItems = new TreeItem("Views", Color.FromArgb(0, 0, 0, 0), "", TreeItem.TreeItemType.View);
			PartItems.Add(GeometryTreeItems);
			PartItems.Add(MarkupTreeItems);
			PartItems.Add(ViewsTreeItems);

			_shown = myTreeView1;
			_shown.DataContext = PartItems;
			_shown.ItemTemplate = (DataTemplate)this.Resources["RootTemplate"];
			Collection<Color> colors = new Collection<Color>();
			colors.Add(Color.FromArgb (255, 255, 255, 255));
			colors.Add(Color.FromArgb(255, 227, 230, 233));
			colors.Add(Color.FromArgb(255, 127, 127, 127));
			colors.Add(Color.FromArgb(255, 0, 0, 0));
			colors.Add(Color.FromArgb(255, 75, 172, 198));
			colors.Add(Color.FromArgb(255, 31, 73, 125));
			colors.Add(Color.FromArgb(255, 16, 37, 63));
			colors.Add(Color.FromArgb(255, 155, 187, 89));
			colors.Add(Color.FromArgb(255, 192, 80, 77));
			colors.Add(Color.FromArgb(255, 247, 150, 70));
			customPaletteView.PaletteColumnsCount = 5;
			customPaletteView.ItemsSource = colors;
		}

		#endregion

		#region Internal Members

		internal ScriptObject MarkupLoad { get; set; }
		internal string xmldata { get; set; }

		internal HtmlElement ViewBrowser
		{
			get { return _viewBrowser; }
			set { _viewBrowser = value; }
		}

		internal void ScreenScroll()
		{
			this.Viewer_SizeChanged(this, null);
		}
		internal void SetBackgroundColor(uint argb)
		{
			uint higha = 0xff000000;
			byte a = (byte)((argb & higha) >> 0x18);
			byte r = (byte)((argb & 0xff0000) >> 0x10);
			byte g = (byte)((argb & 0xff00) >> 8);
			byte b = (byte)(argb & 0xff);
			_color = Color.FromArgb(a, r, g, b);
		}

		internal void AddMarkup(ScriptObject markup)
		{
			double c = 136.0 / 255.0;
			markup.Invoke("SetColor", c, c, c);
			TreeItem newti = new TreeItem(!_markuploading || NameExists(_markupName, MarkupTreeItems.ChildItems) ? MakeUniqueName(!_markuploading ? _markupType : _markupName, MarkupTreeItems.ChildItems) : _markupName, Color.FromArgb(0, 0, 0, 0), "", TreeItem.TreeItemType.Markup);
			newti.Tag = markup;
			bool exists = false;
			foreach (TreeItem ti in MarkupTreeItems.ChildItems)
			{
				if (ti.Tag != null && ti.Tag.Equals (markup))
				{
					exists = true;
					break;
				}
			}
			if (!exists)
			{
				MarkupTreeItems.ChildItems.Add(newti);
			}
		}

		internal void DeleteMarkup(ScriptObject markup)
		{
			foreach (TreeItem ti in MarkupTreeItems.ChildItems)
			{
				if (ti.Tag != null && ti.Tag.Equals(markup))
				{
					MarkupTreeItems.ChildItems.Remove(ti);
					break;
				}
			}
		}

		internal void PickMarkup(ScriptObject markup)
		{
			foreach (TreeItem ti in MarkupTreeItems.ChildItems)
			{
				if (ti.Tag != null && ti.Tag.Equals(markup))
				{
					_shown.SelectedItem = ti;
					break;
				}
			}
		}

		internal void AddModel(int modelnum, string name, XDocument document)
		{
			string parent = "";
			string shortname = name.Substring(name.LastIndexOf('\\') + 1);
			IEnumerator<XElement> els = document.Elements().GetEnumerator();
			els.MoveNext();
			XElement ele = els.Current;
			LoadElements(ele, GeometryTreeItems, parent);
			PruneTree(GeometryTreeItems);
			// Load Existing markups
			LoadMarkups();
			// Load Existing views
			LoadViews();
			PartName.Header = shortname;
		}

		private void AddSeparatorToMenu()
		{
			Telerik.Windows.Controls.RadMenuItem sep = new Telerik.Windows.Controls.RadMenuItem();
			sep.IsSeparator = true;
			sep.Width = 10;
			sep.Height = 10;
			sep.Background = this.Resources["MenuSperatorBrush"] as ImageBrush;
			sep.VerticalAlignment = VerticalAlignment.Center;
			BreadCrumb.Items.Add(sep);
		}

		private void PruneTree(TreeItem item)
		{
			if (item.ChildItems.Count == 1 && item.ChildItems[0].Title == "/")
			{
				ObservableCollection<TreeItem> subs = item.ChildItems[0].ChildItems;
				item.ChildItems.Clear();
				foreach (TreeItem ti in subs)
				{
					item.ChildItems.Add(ti);
				}
			}
			PruneDuplicateSubChildren(item);
		}
		private void PruneDuplicateSubChildren(TreeItem item)
		{
			for (int ii = 0; ii < item.ChildItems.Count; ii++)
			{
				TreeItem ti = item.ChildItems[ii];
				PruneDuplicateSubChildren(ti);
				if (ti.ChildItems.Count == 1 && ti.ChildItems[0].Title == ti.Title)
				{
					item.ChildItems[ii] = ti.ChildItems[0];
				}
			}
		}

		internal bool LoadElements(XElement toAdd, TreeItem parent, string parentid)
		{
			XElement att = toAdd.Element("Name");
			if (att != null)
			{
				string id = parentid + att.Value;
				ScriptObject o = _viewBrowser.Invoke("SceneGetNode", id) as ScriptObject;
				Color c = Color.FromArgb(0, 0, 0, 0);
				if (o != null)
				{
					byte r = Convert.ToByte(Convert.ToSingle(o.GetProperty("ExtColorRed")) * 255.0);
					byte g = Convert.ToByte(Convert.ToSingle(o.GetProperty("ExtColorGreen")) * 255.0);
					byte b = Convert.ToByte(Convert.ToSingle(o.GetProperty("ExtColorBlue")) * 255.0);
					c = Color.FromArgb(255, r, g, b);
				}
				TreeItem newItem = new TreeItem(att.Value, c, id, TreeItem.TreeItemType.Geometry);
				parent.ChildItems.Add(newItem);
				bool loadedPart = false;;
				foreach (XElement ele in toAdd.Elements())
				{
					loadedPart = LoadElements(ele, newItem, parentid + att.Value + "/") || loadedPart;
					XAttribute pid = ele.Attribute("PartID");
					if (pid != null)
					{
						loadedPart = true;
					}
				}
				if (!loadedPart)
				{
					parent.ChildItems.Remove(newItem);
				}
			}
			if (parent.ChildItems.Count > 0)
			{
				Color c = Color.FromArgb(255, 128, 128, 128);
				parent.Color = c;
			}
			return parent.ChildItems.Count > 0;
		}

		internal void SetLeftMouseState (MouseState ms)
		{
			_leftMouseState = ms;
			SetMouseIcons();
		}

		internal void LoadFile(string url, string xml)
		{
			_current = this.Cursor;
			Cursor = Cursors.Wait;
			DownloadComplete(url, xml);
		}

		#endregion

		#region Private Members

		private string MakeUniqueName(string basename, ObservableCollection<TreeItem> items)
		{
			int index = 1;
			string ret = basename + index.ToString();
			while (NameExists(ret, items))
			{
				index++;
				ret = basename + index.ToString();
			}
			return ret;
		}

		private bool NameExists(string name, ObservableCollection<TreeItem> items)
		{
			bool ret = false;
			foreach (TreeItem ti in items)
			{
				if (ti.Title == name)
				{
					ret = true;
					break;
				}
			}
			return ret;
		}

		private void LoadMarkups()
		{
			HtmlPage.Window.Invoke("globalSceneGetFirstMarkup");
			while (MarkupLoad != null)
			{
				bool exists = false;
				foreach (TreeItem ti in MarkupTreeItems.ChildItems)
				{
					if (ti.Tag.Equals(MarkupLoad))
					{
						exists = true;
						break;
					}
				}
				if (!exists)
				{
					string type = MarkupLoad.Invoke("GetType") as string;
					TreeItem newti = new TreeItem(MakeUniqueName(type, MarkupTreeItems.ChildItems), Color.FromArgb (0, 0, 0, 0), "", TreeItem.TreeItemType.Markup);
					newti.Tag = MarkupLoad;
					MarkupTreeItems.ChildItems.Add(newti);
				}
				HtmlPage.Window.Invoke("globalSceneGetNextMarkup");
			}
		}

		private void LoadViews()
		{
			double viewid = (double)_viewBrowser.Invoke("ViewGetFirst");
			while (viewid >= 0)
			{
				bool exists = false;
				foreach (TreeItem ti in ViewsTreeItems.ChildItems)
				{
					if (((double)ti.Tag) == viewid)
					{
						exists = true;
						break;
					}
				}
				if (!exists)
				{
					string name = _viewBrowser.Invoke("ViewGetName", viewid) as string;
					if (NameExists(name, ViewsTreeItems.ChildItems))
					{
						name = MakeUniqueName(name, ViewsTreeItems.ChildItems);
					}
					TreeItem newti = new TreeItem(name, Color.FromArgb(0, 0, 0, 0), "", TreeItem.TreeItemType.View);
					newti.Tag = viewid;
					ViewsTreeItems.ChildItems.Add(newti);
					viewid = (double)_viewBrowser.Invoke("ViewGetNext");
				}
			}
		}

		double offsetTop = 0.0;
		bool virgin = true;

		private void Viewer_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			HtmlElement m = HtmlPage.Document.GetElementById("ActifyControl");
			HtmlElement b = HtmlPage.Document.GetElementById("xviewBrowser");
			HtmlElement s = HtmlPage.Document.GetElementById("silverlightControlHost");
			if (false && virgin && m != null && s != null)
			{
				offsetTop = (double)m.GetProperty("offsetTop");
				offsetTop += (double)s.GetProperty("offsetTop");
				virgin = false;
			}
			if (b != null && m != null)
			{
				double height = ThePanel.ActualHeight;
				GeneralTransform gt = ViewerButton.TransformToVisual(Application.Current.RootVisual as UIElement);
				Point offset = gt.Transform(new Point(0, 0));
				m.SetStyleAttribute("left", string.Format ("{0}px", Convert.ToInt32(offset.X)));
				double top = offset.Y - height;
				m.SetStyleAttribute("top", string.Format("{0}px", Convert.ToInt32(top)));
				b.SetStyleAttribute("width", string.Format ("{0}px", Convert.ToInt32(ViewerButton.ActualWidth)));
				b.SetStyleAttribute("height", string.Format("{0}px", Convert.ToInt32(ViewerButton.ActualHeight)));
				m.SetStyleAttribute("visibility", "visible");
			} 

		}

		private void ClearModels_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalClearModels");
			GeometryTreeItems.ChildItems.Clear();
		}

		private void Rotate_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalViewSetMouseAction", "ROTATE");
		}

		private void Zoom_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalViewSetMouseAction", "ZOOM");
		}

		private void Pan_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalViewSetMouseAction", "PAN");
		}
		private void SetMouseIcons()
		{
			RotateButton.LargeImage = _leftMouseState == MouseState.Rotate ? _rh.GetBitmap("Images/Rotate pushed.png") : _rh.GetBitmap("Images/Rotate Unpushed red.png");
			PanButton.LargeImage = _leftMouseState == MouseState.Pan ? _rh.GetBitmap("Images/Pan pushed.png") : _rh.GetBitmap("Images/Pan unpushed red.png");
			ZoomButton.LargeImage = _leftMouseState == MouseState.Zoom ? _rh.GetBitmap("Images/Zoom pushed.png") : _rh.GetBitmap("Images/Zoom Unpushed red.png");
		}

		private void FitAll_Button_Click(object sender, RoutedEventArgs e)
		{
			Cursor current = this.Cursor;
			this.Cursor = Cursors.Wait;
			HtmlPage.Window.Invoke("globalViewZoomFit");
			this.Cursor = current;
		}

		private void Zoom_Win_Button_Click(object sender, RoutedEventArgs e)
		{
			spinStoryBoard.SetValue(Storyboard.TargetNameProperty, "projectionZoomWin");
//			spinStoryBoard.Begin();
			_viewBrowser.Invoke("ViewZoomWindow", 0);
		}

		private void Focus_On_Point_Click(object sender, RoutedEventArgs e)
		{
			spinStoryBoard.SetValue(Storyboard.TargetNameProperty, "projectionFocusOnPoint");
//			spinStoryBoard.Begin();
			_viewBrowser.Invoke("PickingType", "POINTS");
			HtmlPage.Window.Invoke("globalFocusOnPoint");
		}

		private void Focus_On_Part_Click(object sender, RoutedEventArgs e)
		{
			spinStoryBoard.SetValue(Storyboard.TargetNameProperty, "projectionFocusOnPart");
//			spinStoryBoard.Begin();
			_viewBrowser.Invoke("PickingType", "PARTS");
			HtmlPage.Window.Invoke("globalFocusOnPart");
		}

		private void Note_Button_Click(object sender, RoutedEventArgs e)
		{
			_markuploading = false;
			_markupType = "Note";
			_viewBrowser.Invoke("PickingType", "POINTS");
			HtmlPage.Window.Invoke("globalCreateMarkup", _markupType);
		}

		private void Distance_Button_Click(object sender, RoutedEventArgs e)
		{
			_markuploading = false;
			_markupType = "Distance";
			_viewBrowser.Invoke("PickingType", "POINTS");
			HtmlPage.Window.Invoke("globalCreateMarkup", _markupType);
		}

		private void Bounding_Box_Button_Click(object sender, RoutedEventArgs e)
		{
			_markuploading = false;
			_markupType = "BoundBox";
			_viewBrowser.Invoke("PickingType", "PARTS");
			HtmlPage.Window.Invoke("globalCreateMarkup", _markupType);
		}

		private void Mass_Properties_Button_Click(object sender, RoutedEventArgs e)
		{
			_markuploading = false;
			_markupType = "MassProperties";
			_viewBrowser.Invoke("PickingType", "PARTS");
			HtmlPage.Window.Invoke("globalCreateMassMarkup", _markupType);
		}

		private void View_GoTo_Button_Click(object sender,RoutedEventArgs e)
		{
			_viewBrowser.Invoke("EnableDisplay", 0);
			Image b = e.OriginalSource as Image;
			StackPanel sp = b.Parent as StackPanel;
			TreeItem ti = sp.DataContext as TreeItem;
			if (ti != null)
			{
				if (ti.ItemType == TreeItem.TreeItemType.View)
				{
					_viewBrowser.Invoke("ViewApply", Convert.ToInt32(ti.Tag), 0);
				}
			}
			_viewBrowser.Invoke("EnableDisplay", -1);
		}

		private void MarkupShow_Button_Click(object sender, RoutedEventArgs e)
		{
			_viewBrowser.Invoke("EnableDisplay", 0);
			Image b = e.OriginalSource as Image;
			StackPanel sp = b.Parent as StackPanel;
			TreeItem ti = sp.DataContext as TreeItem;
			int index = _shown.Items.IndexOf(ti);
			if (ti != null && ti.ItemType == TreeItem.TreeItemType.Markup)
			{
				bool isvisible = ti.Visible;
				isvisible = !isvisible;
				ScriptObject o = ti.Tag as ScriptObject;
				if (o != null)
				{
					o.Invoke("SetVisible", isvisible ? -1 : 0);
				}
				ti.Visible = isvisible;
				b.Source = ti.ShowHideImage;
			}
			_viewBrowser.Invoke("EnableDisplay", -1);
		}

		private void ModelShow_Button_Click(object sender, RoutedEventArgs e)
		{
			_viewBrowser.Invoke("EnableDisplay", 0);

			System.Windows.Shapes.Shape sh = e.OriginalSource as System.Windows.Shapes.Shape;
			Grid grid = sh.Parent as Grid;
			System.Windows.Shapes.Ellipse b = grid.Children[0] as System.Windows.Shapes.Ellipse;
			System.Windows.Shapes.Line line1 = grid.Children[1] as System.Windows.Shapes.Line;
			System.Windows.Shapes.Line line2 = grid.Children[2] as System.Windows.Shapes.Line;
			StackPanel sp = grid.Parent as StackPanel;
			TreeItem ti = sp.DataContext as TreeItem;
			int index = _shown.Items.IndexOf(ti);
			if (ti != null && ti.ItemType == TreeItem.TreeItemType.Geometry)
			{
				bool isvisible = ti.Visible;
				isvisible = !isvisible;
				string id = ti.Path;
				ScriptObject o = _viewBrowser.Invoke("SceneGetNode", id) as ScriptObject;
				if (o != null)
				{
					o.Invoke("Hide", isvisible ? 0 : -1);
				}
				ti.Visible = isvisible;
				((SolidColorBrush)b.Fill).Color = isvisible ? ti.Color : Color.FromArgb(0, 0, 0, 0);
				((SolidColorBrush)line1.Stroke).Color = isvisible ? Color.FromArgb(0, 0, 0, 0) : Color.FromArgb(255, 81, 81, 81);
				((SolidColorBrush)line2.Stroke).Color = isvisible ? Color.FromArgb(0, 0, 0, 0) : Color.FromArgb(255, 81, 81, 81);
			}
			_viewBrowser.Invoke("EnableDisplay", -1);
		}

		private void ModelZoom_Button_Click(object sender, RoutedEventArgs e)
		{
			_viewBrowser.Invoke("EnableDisplay", 0);
			Image b = e.OriginalSource as Image;
			StackPanel sp = b.Parent as StackPanel;
			TreeItem ti = sp.DataContext as TreeItem;
			if (ti != null && ti.ItemType == TreeItem.TreeItemType.Geometry)
			{
				string id = ti.Path;
				ScriptObject o = _viewBrowser.Invoke("SceneGetNode", id) as ScriptObject;
				if (o != null)
				{
					if (ti.Highlighted)
					{
						o.Invoke("Hilight", 0);
					}
					o.Invoke("Focus");
					if (ti.Highlighted)
					{
						o.Invoke("Hilight", -1);
					}
				}
			}
			_viewBrowser.Invoke("EnableDisplay", -1);
		}

		private void SaveMarkup_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string markup = "<?xml version=\"1.0\" encoding=\"utf-8\"?><markups>";
				foreach (TreeItem ti in MarkupTreeItems.ChildItems)
				{
					if (ti.Tag != null)
					{
						string name = ti.Title;
						ScriptObject so = ti.Tag as ScriptObject;
						string xml = so.Invoke("GetXML") as string;
						markup += string.Format("<markup name=\"{0}\">", name);
						xml = xml.Replace("\r\n", " ");
						markup += string.Format("{0}</markup>", xml);
					}
				}
				markup += "</markups>";

                HtmlPage.Window.Invoke("globalSaveMarkup", markup);
			}
			catch (Exception)
			{
				MessageBox.Show("Saving Markup failed");
			}
		}

		private void LoadMarkup_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
				{
					using (IsolatedStorageFileStream stream = store.OpenFile("markup.txt", FileMode.Open))
					{
						_markuploading = true;
						StreamReader sr = new StreamReader(stream);
						while (!sr.EndOfStream)
						{
							_markupName = sr.ReadLine();
							string xml = sr.ReadLine();
							HtmlPage.Window.Invoke("globalCreateMarkupXml", xml);
						}
						sr.Close();
					}
				}
			}
			catch (Exception)
			{
				MessageBox.Show("Loading Markup failed");
			}
		}

		private void Tree_Window_Button_Click(object sender, RoutedEventArgs e)
		{
			GridLength last = Column1.Width;
			Column1.Width = _treeWidthLast;
			_treeWidthLast = last;
			last = Splitter.Width;
			Splitter.Width = _splitterWidthLast;
			_splitterWidthLast = last;
			ShowHideTree.Text = Column1.Width.Equals(_treeWidthZero) ? "Navigator On" : "Navigator Off";
		}

		private void CS_Display_Button_Click(object sender, RoutedEventArgs e)
		{
			int state = Convert.ToInt32(_viewBrowser.GetProperty("ReferenceFrame"));
			_viewBrowser.SetProperty("ReferenceFrame", state == 0 ? 1 : 0);
			ShowCoordSystems.Text = state == 1 ? "Show CS" : "Hide CS";
		}

		private void LoadMarkup(string name, string data)
		{
			if (!NameExists(name, MarkupTreeItems.ChildItems))
			{
				_markuploading = true;
				_markupName = name;
				HtmlPage.Window.Invoke("globalCreateMarkupXml", data);
			}
		}

		private void DownloadComplete(string model, string xml)
		{
			try
			{
				HtmlPage.Window.Invoke("globalFileLoad", model);
				if (xml != "")
				{
					XDocument document = XDocument.Parse(xml);
					IEnumerator<XElement> els = document.Elements().GetEnumerator();
					if (els != null)
					{
						els.MoveNext();
						if (els != null)
						{
							XElement ele = els.Current;
							if (ele != null)
							{
								foreach (XElement mu in ele.Elements())
								{
									XAttribute muname = mu.Attribute("name");
									if (muname != null)
									{
										foreach (XElement mudata in mu.Elements())
										{
											string data = mudata.ToString();
											LoadMarkup(muname.Value, data);
											break;
										}
									}
								}
							}
						}
					}
				}
			}
			catch (Exception)
			{
			}
			Cursor = _current;
		}

		private void Shaded_Smooth_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalSetShadingMode", 1);
		}

		private void Shaded_Smoth_With_Edges_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalSetShadingMode", 6);
		}

		private void WireframeAll_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalSetShadingMode", 2);
		}

		private void WireframeHLR_Button_Click(object sender, RoutedEventArgs e)
		{
			HtmlPage.Window.Invoke("globalSetShadingMode", 4);
		}

		internal void SetRenderIcons()
		{
			HtmlPage.Window.Invoke("globalGetShadingMode");
		}

		internal void SetRenderIcons(short mode)
		{
			ShadedSmoothButton.LargeImage = mode == 1.0 ? _rh.GetBitmap("Images/smooth 256x256.png") : _rh.GetBitmap("Images/smooth off 256x256.png");
			ShadedSmothWithEdgesButton.LargeImage = mode == 6.0 ? _rh.GetBitmap("Images/smooth edges 256x256.png") : _rh.GetBitmap("Images/smooth edges off 256x256.png");
			WireframeAllButton.LargeImage = mode == 2.0 ? _rh.GetBitmap("Images/wire visible 256x256.png") : _rh.GetBitmap("Images/wire visible off 256x256.png");
			WireframeHLRButton.LargeImage = mode == 4.0 ? _rh.GetBitmap("Images/wire hidden 256x256.png") : _rh.GetBitmap("Images/wire hidden off 256x256.png");
		}

		internal void ResetHighlight()
		{
			if (_lasthighlighted != null)
			{
				_viewBrowser.Invoke("EnableDisplay", 0);
				_lasthighlighted.Invoke("Hilight", 0);
				_viewBrowser.Invoke("EnableDisplay", -1);
				_lasthighlighted.Invoke("Hilight", -1);
			}
		}

		private void color_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			System.Windows.Shapes.Rectangle rect = e.OriginalSource as System.Windows.Shapes.Rectangle;
			SolidColorBrush scb = rect.Fill as SolidColorBrush;
			_color = scb.Color;
			uint c = /*((uint) _color.A << 24) |*/ ((uint) _color.B << 16) | ((uint) _color.G << 8) | (uint) _color.R;
			_viewBrowser.SetProperty("RGBBackgroundColor", c);
		}

		private void PerspectiveIsometric_Display_Button_Click(object sender, EventArgs e)
		{
			bool o = (bool)_viewBrowser.Invoke("ViewGetPerspective", 0);
			o = !o;
			_viewBrowser.Invoke("ViewSetPerspective", 0, o ? -1 : 0);
			PerspectiveIsometric.Text = o ? "Isometric" : "Perspective";
			PerspectiveIsometric.LargeImage = o ? _rh.GetBitmap("Images/iso 256x256.png") : _rh.GetBitmap("Images/perspective 256x256.png");
		}

		#endregion

		private void myTreeView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
		{
			_viewBrowser.Invoke("EnableDisplay", 0);
			foreach (TreeItem ti in e.RemovedItems)
			{
				string id = ti.Path;
				ti.Highlighted = false;
				_lasthighlighted = null;
				ScriptObject o = _viewBrowser.Invoke("SceneGetNode", id) as ScriptObject;
				if (o != null)
				{
					bool p = (bool)o.Invoke("IsHidden");
					if (!p)
					{
						o.Invoke("Hilight", 0);
					}
				}
			}
			foreach (TreeItem ti in e.AddedItems)
			{
				if (ti.ItemType == TreeItem.TreeItemType.Geometry)
				{
					string id = ti.Path;
					ScriptObject o = _viewBrowser.Invoke("SceneGetNode", id) as ScriptObject;
					if (o != null)
					{
						bool p = (bool)o.Invoke("IsHidden");
						if (!p)
						{
							_lasthighlighted = o;
							ti.Highlighted = true;
							o.Invoke("Hilight", -1);
						}
					}
				}
			}
			_viewBrowser.Invoke("EnableDisplay", -1);
		}

		private void myTreeView_Expanded(object sender, Telerik.Windows.RadRoutedEventArgs e)
		{
			Telerik.Windows.Controls.RadTreeView hidden = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			SlideAway.To = _shown.ActualWidth;
			spinTree.SetValue(Storyboard.TargetNameProperty, _shown == myTreeView1 ? "projectionMyTreeView1" : "projectionMyTreeView2");
			spinTree.Begin();
			Telerik.Windows.Controls.RadTreeViewItem item = e.Source as Telerik.Windows.Controls.RadTreeViewItem;
			TreeItem ti = item.Header as TreeItem;
			ObservableCollection<TreeItem> nextList = null;
			DataTemplate nextTemplate = null;
			if (ti != null)
			{
				switch (ti.ItemType)
				{
					case TreeItem.TreeItemType.Geometry:
						nextList = ti.ChildItems;
						nextTemplate = (DataTemplate)this.Resources["GeometryTemplate"];
						break;
					case TreeItem.TreeItemType.Markup:
						nextList = MarkupTreeItems.ChildItems;
						nextTemplate = (DataTemplate)this.Resources["MarkupNameTemplate"];
						break;
					case TreeItem.TreeItemType.RootNode:
						nextList = PartItems;
						nextTemplate = (DataTemplate)this.Resources["RootTemplate"];
						break;
					case TreeItem.TreeItemType.View:
						nextList = ViewsTreeItems.ChildItems;
						nextTemplate = (DataTemplate)this.Resources["ViewNameTemplate"];
						break;
				}
				Thickness t = _shown.BorderThickness;
				t.Left = 1;
				_shown.BorderThickness = t;
				hidden.DataContext = nextList;
				hidden.ItemTemplate = nextTemplate;
				BreadCrumbAdd.Stop();
				if (_toAddRmi != null)
				{
					_toAddRmi.FontWeight = System.Windows.FontWeights.Normal;
				}
				_toAddRmi = new Telerik.Windows.Controls.RadMenuItem();
				_toAddRmi.Header = ti.Title;
				_toAddRmi.Tag = ti;
				_toAddRmi.FontWeight = System.Windows.FontWeights.ExtraBold;
				_toAddRmi.Click += new Telerik.Windows.RadRoutedEventHandler(rmi_Click);
				_toAddRmi.Name = System.Guid.NewGuid().ToString();
				AddSeparatorToMenu();
				BreadCrumb.Items.Add(_toAddRmi);
				BreadCrumbAdd.SetValue(Storyboard.TargetNameProperty, _toAddRmi.Name);
				BreadCrumbAdd.Begin();
			}
		}

		void rmi_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
		{
			_shown = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			Canvas.SetZIndex(_shown == myTreeView1 ? myTreeView2 : myTreeView1, -1);
			Canvas.SetZIndex(_shown, 0);
			spinTreeBack.SetValue(Storyboard.TargetNameProperty, _shown == myTreeView1 ? "projectionMyTreeView1" : "projectionMyTreeView2");
			Telerik.Windows.Controls.RadMenuItem rmi = e.Source as Telerik.Windows.Controls.RadMenuItem;
			TreeItem ti = rmi.Tag as TreeItem;
			_shown.DataContext = ti.ChildItems;
			SlideAway.To = _shown.ActualWidth;
			Thickness t = _shown.BorderThickness;
			t.Left = 1;
			_shown.BorderThickness = t;
			spinTreeBack.Begin();
			int remto = BreadCrumb.Items.IndexOf(rmi) + 1;
			while (BreadCrumb.Items.Count > remto)
			{
				BreadCrumb.Items.RemoveAt(BreadCrumb.Items.Count - 1);
			}
		}

		private void PartName_Click(object sender, Telerik.Windows.RadRoutedEventArgs e)
		{
			_shown = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			Canvas.SetZIndex(_shown == myTreeView1 ? myTreeView2 : myTreeView1, -1);
			Canvas.SetZIndex(_shown, 0);
			spinTreeBack.SetValue(Storyboard.TargetNameProperty, _shown == myTreeView1 ? "projectionMyTreeView1" : "projectionMyTreeView2");
			SlideAway.To = _shown.ActualWidth;
			_shown.DataContext = PartItems;
			_shown.ItemTemplate = (DataTemplate)this.Resources["RootTemplate"];
			Thickness t = _shown.BorderThickness;
			t.Left = 1;
			_shown.BorderThickness = t;
			spinTreeBack.Begin();
			while (BreadCrumb.Items.Count > 1)
			{
				BreadCrumb.Items.RemoveAt(BreadCrumb.Items.Count - 1);
			}
		}

		private void DoubleAnimation_Completed(object sender, EventArgs e)
		{
			Thickness t = _shown.BorderThickness;
			t.Left = 0;
			_shown.BorderThickness = t;
			_shown = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			Canvas.SetZIndex(_shown == myTreeView1 ? myTreeView2 : myTreeView1, -1);
			Canvas.SetZIndex(_shown, 0);
			spinTree.Stop();
			Telerik.Windows.Controls.RadTreeView hidden = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			hidden.DataContext = null;
			spinTreeBack.SetValue(Storyboard.TargetNameProperty, _shown == myTreeView1 ? "projectionMyTreeView1" : "projectionMyTreeView2");
		}
		private void DoubleAnimationBack_Completed(object sender, EventArgs e)
		{
			Thickness t = _shown.BorderThickness;
			t.Left = 0;
			_shown.BorderThickness = t;
			spinTreeBack.Stop();
			Telerik.Windows.Controls.RadTreeView hidden = _shown == myTreeView1 ? myTreeView2 : myTreeView1;
			hidden.DataContext = null;
		}

		private void ColorAnimation_Completed(object sender, EventArgs e)
		{
			BreadCrumbAdd.Stop();
			if (_toAddRmi != null)
			{
				_toAddRmi.FontWeight = System.Windows.FontWeights.Normal;
				_toAddRmi = null;
			}
		}

		private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			myTreeView1.Width = TreeCanvas.ActualWidth;
			myTreeView1.Height = TreeCanvas.ActualHeight;
			myTreeView2.Width = TreeCanvas.ActualWidth;
			myTreeView2.Height = TreeCanvas.ActualHeight;
		}

		private void ThePanel_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
		{

		}
	}
}
